﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base.UOM;
using UFIDA.U9.CBO.HR.Nation;
using UFIDA.U9.CBO.SCM.Item;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class ItemConvertRatioBase
    {
        public static ItemConvertRatioOverClass GetEntity(ItemConvertRatioAITDTOData dto)
        {
            if (dto.ItemMaster == null) throw new Exception("ItemMaster必填");
            if (dto.FromUOM == null) throw new Exception("FromUOM必填");
            if (dto.ToUOM == null) throw new Exception("ToUOM必填");

            string path = $"ItemMaster.Code='{dto.ItemMaster.Code}' and FromUOM.Code='{dto.FromUOM.Code}' and ToUOM.Code='{dto.ToUOM.Code}'";
            ItemConvertRatioOverClass entity = ItemConvertRatioOverClass.Finder.Find(path);
            return entity;
        }

        /// <summary>
        /// 创建组间转换率
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ItemConvertRatioOverClass CreateDoc(ItemConvertRatioAITDTOData dto)
        {
            ItemConvertRatioOverClass ratio = null;

            if (dto.ItemMaster == null) throw new Exception("ItemMaster必填");
            ItemMaster item = EntityUtils.GetEntityByCode<ItemMaster>(dto.ItemMaster.Code);
            if (dto.FromUOM == null) throw new Exception("FromUOM必填");
            UOM from = EntityUtils.GetEntityByCode<UOM>(dto.FromUOM.Code);
            if (dto.ToUOM == null) throw new Exception("ToUOM必填");
            UOM to = EntityUtils.GetEntityByCode<UOM>(dto.ToUOM.Code);
            if (from.ID == to.ID) return null ;
            if (dto.Ratio == 0) throw new Exception("Ratio不能为0");

            using(ISession session = Session.Open())
            {
                ratio = ItemConvertRatioOverClass.Create(item);
                ratio.FromUOM = from;
                ratio.ToUOM = to;
                ratio.Ratio = dto.Ratio;

                session.Commit();
            }

            return ratio;
        }
        /// <summary>
        /// 修改转换率
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public static ItemConvertRatioOverClass UpdateDoc(ItemConvertRatioAITDTOData dto, ItemConvertRatioOverClass item)
        {
            using (ISession session = Session.Open())
            {
                item = item.Key.GetEntity();
                item.Ratio = dto.Ratio;

                session.Commit();
            }

            return item;
        }
    }
}
